#!/bin/bash

# usage check
if [ ! -d $1 ]; then
	echo "Usage: buildbundle <bundle dir>" 1>&2
	exit 1
fi
if [ -z "$BUNDLEDIR" -o ! -e $BUNDLEDIR/run.bash ]; then
	echo "Enviornmental variable BUNDLEDIR must be set to bundle contrib files" 1>&2
	exit 1
fi

# set up useful variables
DIR=$1
CONTRIB=$BUNDLEDIR

# exec config file
if [ ! -e $DIR/config ]; then
	echo "Error: $DIR/config not found!" 2>&1
	exit 1
fi
. $DIR/config

# check config variables
if [ -z "$TYPE" -o -z "$FILES" -o -z "$NAME" -o -z "$VERSION" ]; then
	echo "Error: config.bash must define variables: TYPE, NAME, VERSION, FILES" 1>&2
	exit 1
fi

# check to see if zip already exists
if [ -e "$NAME-$VERSION.stuff" ]; then
	echo "Bundle file has already been built. Remove it to rebuild." 1>&2
	exit 1
fi

TDIR=`tempfile -p "dply-" -s "-$NAME"`
rm -f $TDIR
mkdir $TDIR

# copying files
function cleanupquit {
	rm -rf $TDIR
	exit $1
}

function copyuser {
	# if second param is set, ignore if not exist
	
	if [ "$1" = "$NAME-$VERSION.stuff" ]; then
		echo "Error: Illegal file name: $1" 1>&2
		cleanupquit 1
	elif [ ! -e "$DIR/$1" -a -z "$2" ]; then
		echo "Error: File $1 doesn't exist!" 1>&2
		cleanupquit 1
	elif [ -e "$TDIR/$1" ]; then
		echo "Error: Duplicate file $1!" 1>&2
		cleanupquit 1
	fi
	
	if [ -e "$DIR/$1" ]; then
		mkdir -p `dirname $TDIR/$1`
		cp $DIR/$1 $TDIR/$1
	fi
}

function copycontrib {
	if [ -e "$TDIR/$1" ]; then
		echo "Error: File $1 conflicts with platform file!" 1>&2
		cleanupquit 1
	fi
	
	if [ ! -e "$CONTRIB/$1" ]; then
		echo "Error: Platform file $1 doesn't exist! Check BUNDLEDIR variable" 1>&2
		cleanupquit 1
	fi
	
	mkdir -p `dirname $TDIR/$1`
	cp $CONTRIB/$1 $TDIR/$1
}

for fname in ${FILES[@]}; do
	copyuser $fname
done

# copy user files
copyuser check.part.bash	i
copyuser install.part.bash	i
copyuser uninstall.part.bash	i
copyuser upgrade.part.bash	i
copyuser config
if [ ! -z "$ICON" ]; then
	copyuser $ICON
fi

# copy contrib files
if [ "$TYPE" = "application" ]; then
	copycontrib run.bash
	copycontrib bundlepeer
	copycontrib master.install.bash
	copycontrib master.uninstall.bash
elif [ "$TYPE" = "upgrade" ]; then
	copycontrib master.upgrade.bash
else
	echo "Error: Unknown bundle type: $TYPE" 1>&2
	cleanupquit 1
fi

# generate ID in config file
cat $TDIR/* 2>/dev/null | md5sum | awk '{print "\nBID="$1"\n"}' >>$TDIR/config


# zipping archive
( cd $TDIR; zip -r "$NAME-$VERSION.stuff" * >/dev/null )
cp "$TDIR/$NAME-$VERSION.stuff" .

echo "OUTPUT FILE: $NAME-$VERSION.stuff"
cleanupquit 0

